package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
)

// 用户登录接口
func Login(ctx *gin.Context) {
	email := ctx.PostForm("email")
	password := ctx.PostForm("password")

	var user model.User
	// 构建数据库查询条件
	DB := common.GetDB()
	DB.Where("email = ? or backupemail=?", email, email).First(&user)

	if user.UID == 0 {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "邮箱不存在",
		})
		return
	}
	//校验密码
	dbPassword := user.Password
	hashedDBPassword, error := bcrypt.GenerateFromPassword([]byte(dbPassword), bcrypt.DefaultCost)
	if error != nil {
		// 处理哈希错误
		response.Response(ctx, http.StatusInternalServerError, 100, nil, "加密错误！")
		return
	}
	if err := bcrypt.CompareHashAndPassword(hashedDBPassword, []byte(password)); err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	response.Success(ctx, gin.H{"user": user}, "登录成功")
}
